import axios from 'axios';

import router from '@/router';

const API_URL = 'http://localhost:8081/'; // 后端地址

// 创建 axios 实例
const instance = axios.create({
    baseURL: API_URL,
});


//添加请求拦截器
//axios的请求 request 拦截器, 每次请求获取localStorage中的loginUser, 从中获取到token, 在请求头token中携带到服务端
instance.interceptors.request.use(
    (config) => {
        //在发生请求时做些什么
        //let loginUser = JSON.parse(localStorage.getItem('loginUser'))
        let loginUser = localStorage.getItem('loginUser')
        console.log(localStorage.getItem('loginUser'))
        if (loginUser) {
            config.headers.token = loginUser;
        }
        return config;
    },
    (error) => {
        //对请求错误做些什么
        console.log('请求错误',error);
        return Promise.reject(error);
    }
);

//添加响应拦截器
instance.interceptors.response.use(
    (response) => {
        //对响应数据做些什么
        console.log('响应数据',response);
        return response;
    },
    (error) => {
        //对响应错误做些什么
        if (error != null) {
            // 401 错误处理
            console.log('401错误');
            router.push('/login');
        }
        console.log('响应错误',error);
        return Promise.reject(error);
    }
);


export const fetchData = async (path) => {
    try {
        const response = await instance.get(`${API_URL}${path}`);
        return response.data;
    } catch (error) {
        console.error('请求数据失败:', error);
        throw error;
    }
};

export const postData = async (path, data) => {
    try {
        const response = await instance.post(`${API_URL}${path}`, data);
        return response.data;
    } catch (error) {
        console.error('提交数据失败:', error);
        throw error;
    }
};

export const analyzeMessage = (url, data) => {
    return postData(url, data);
};
